package com.mo.admin.common.utils;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Objects;

public class RequestResponseUtils {

    // 获取当前的HttpServletRequest
    public static HttpServletRequest getCurrentRequest() {
        return ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
    }

    // 获取当前的HttpServletResponse
    public static HttpServletResponse getCurrentResponse() {
        return ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getResponse();
    }

    // 获取请求URL
    public static String getRequestUrl() {
        HttpServletRequest request = getCurrentRequest();
        return request.getRequestURL().toString();
    }

    // 获取请求IP
    public static String getClientIp() {
        HttpServletRequest request = getCurrentRequest();
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.isEmpty()) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    // 获取请求参数
    public static String getRequestParam(String param) {
        HttpServletRequest request = getCurrentRequest();
        return request.getParameter(param);
    }

    // 设置响应状态码
    public static void setResponseStatus(int statusCode) {
        HttpServletResponse response = getCurrentResponse();
        if (response != null) {
            response.setStatus(statusCode);
        }
    }
}